const path=require("path");
const Koa=require("koa");
const logger=require("koa-logger");
const onerror=require("koa-onerror");
const serve=require("koa-static");
const koaBody=require("koa-body");
const router=require("./router");

const app=new Koa();
app.use(logger());
onerror(app);

app.use(koaBody({
    multipart:true,
    formidable:{
        uploadDir:path.join(__dirname,'./public/upload'),
        keepExtensions:true
    }
}));
let staticPath=path.join(__dirname,'./public');
app.use(serve(staticPath));
app.use(async function(ctx,next){
    ctx.set("Access-Control-Allow-Origin","*");//允许指定域名的跨源请求
    ctx.set("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE,PATCH");
    ctx.set("Access-Control-Allow-Headers","Content-Type,test,Authorization");
    if(ctx.method=="OPTIONS"){
        ctx.body = "";
    }else{
        await next();
    }
})

const token = require("jsonwebtoken");
let tokenConfig = { 
    sign:token.sign,
    secret:"itant secret" 
}

app.use( async function(ctx,next){
    try {
        ctx.token = tokenConfig;
        await next();
    } catch (error) {
        if(error.status==401){
            ctx.status = 401;
            ctx.body = {
                state:false,
                msg:"未授权"
            }
        }else{
            throw error;
        }
    }
} )

const jwt = require("koa-jwt");
app.use( jwt(tokenConfig).unless( { path:[/^\/public\//] } ) )
app.use(router.public.routes());
app.use(router.private.routes());



app.listen(3000);